<script setup lang="ts">
// 保持单一导入（删除重复导入）
import { ref, onMounted } from "vue";
import { LMap, LTileLayer, LGeoJson, LControl } from "@vue-leaflet/vue-leaflet";
import "leaflet/dist/leaflet.css";
import { useMapStore } from "../stores/mapStore";

const mapStore = useMapStore();
const mapRef = ref(null);
const mapReady = ref(false); // 只声明一次

onMounted(async () => {
  // 确保 Leaflet 的 CSS 已加载
  if (typeof L === "undefined") {
    console.error("Leaflet not loaded!");
    return;
  }

  // 修复默认图标路径问题
  delete (L.Icon.Default.prototype as any)._getIconUrl;
  L.Icon.Default.mergeOptions({
    iconRetinaUrl: require("leaflet/dist/images/marker-icon-2x.png"),
    iconUrl: require("leaflet/dist/images/marker-icon.png"),
    shadowUrl: require("leaflet/dist/images/marker-shadow.png"),
  });

  mapReady.value = true;
});
</script>

<template>
  <div class="map-container">
    <l-map
      ref="mapRef"
      :zoom="7"
      :center="[31.22, 112.42]"
      :options="{ zoomControl: false }"
    >
      <!-- 使用OpenStreetMap底图 -->
      <l-tile-layer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      />

      <!-- 湖北省矢量数据 -->
      <l-geo-json
        v-if="mapStore.geoJsonData"
        :geojson="mapStore.geoJsonData"
        :options="{
          style: mapStore.areaStyle,
          onEachFeature: mapStore.onEachFeature,
        }"
      />
    </l-map>
  </div>
</template>

<style scoped>
.map-container {
  height: 100vh;
  width: 100%;
}
</style>
